<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="菜单名称" prop="menuName">
        <el-input
          v-model="queryParams.menuName"
          placeholder="请输入菜单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="父菜单ID" prop="parentId">
        <el-input
          v-model="queryParams.parentId"
          placeholder="请输入父菜单ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜单标题" prop="menuTitle">
        <el-input
          v-model="queryParams.menuTitle"
          placeholder="请输入菜单标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="显示顺序" prop="orderNum">
        <el-input
          v-model="queryParams.orderNum"
          placeholder="请输入显示顺序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="展示地址" prop="showUrl">
        <el-input
          v-model="queryParams.showUrl"
          placeholder="请输入展示地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜单类型" prop="menuType">
        <el-select v-model="queryParams.menuType" placeholder="请选择菜单类型" clearable>
          <el-option
            v-for="dict in dict.type.zx_menu_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="菜单状态" prop="visible">
        <el-select v-model="queryParams.visible" placeholder="请选择菜单状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否展示父级" prop="isShowParent">
        <el-input
          v-model="queryParams.isShowParent"
          placeholder="请输入是否展示父级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
	    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bi:bi_show:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="bi_showList"
      row-key="menuId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="菜单名称" prop="menuName" width="200"/>
      <el-table-column label="父菜单ID" align="center" prop="parentId" />
      <el-table-column label="菜单logo" align="center">
        <template slot-scope="scope">
          <image-preview
            v-if="scope.row.menuLogo"
            :src="scope.row.menuLogo"
            alt="菜单logo"
            style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;"
          />
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="菜单标题" align="center" prop="menuTitle" />
      <el-table-column label="显示顺序" align="center" width="130">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.orderNum"
            :min="0"
            size="mini"
            @change="handleOrderNumChange(scope.row)"
            controls-position="right"
            style="width: 100px;"
          />
        </template>
      </el-table-column>
      <el-table-column label="展示地址" align="center" width="180">
        <template slot-scope="scope">
          <template v-if="scope.row.showUrl">
            <a
              :href="formatUrl(scope.row.showUrl)"
              target="_blank"
              rel="noopener noreferrer"
              style="color: #409EFF; text-decoration: none;"
              @click.stop
            >
              查看
            </a>
          </template>
          <span v-else>无</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="上传文件地址" align="center" prop="fileUrl" />-->
      <el-table-column label="菜单类型" align="center" prop="menuType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.zx_menu_type" :value="scope.row.menuType"/>
        </template>
      </el-table-column>
      <el-table-column label="菜单状态" align="center" prop="visible" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.visible"
            :active-value="'Y'"
            :inactive-value="'N'"
            @change="handleVisibleChange(scope.row)"
          />
        </template>
      </el-table-column>
<!--      <el-table-column label="是否展示父级" align="center" prop="isShowParent">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isShowParent"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="菜单图标" align="center" prop="icon" />-->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bi:bi_show:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['bi:bi_show:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bi:bi_show:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改产品展示信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="父菜单ID" prop="parentId">
          <treeselect v-model="form.parentId" :options="bi_showOptions" :normalizer="normalizer" placeholder="请选择父菜单ID" />
        </el-form-item>
        <el-form-item label="菜单logo" prop="menuLogo">
          <el-input v-model="form.menuLogo" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="上传菜单logo图片" prop="menuLogo">
          <image-upload v-model="form.menuLogo" :fileSize="15"/>
        </el-form-item>
        <el-form-item label="菜单标题" prop="menuTitle">
          <el-input v-model="form.menuTitle" placeholder="请输入菜单标题" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number
            v-model="form.orderNum"
            :min="0"
            :max="9999"
            controls-position="right"
            placeholder="请输入显示顺序"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="展示地址" prop="showUrl">
          <el-input v-model="form.showUrl" placeholder="请输入展示地址" />
        </el-form-item>
        <el-form-item label="上传文件地址" prop="fileUrl">
          <file-upload v-model="form.fileUrl"/>
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-select v-model="form.menuType" placeholder="请选择菜单类型">
            <el-option
              v-for="dict in dict.type.zx_menu_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单状态" prop="visible">
          <el-radio-group v-model="form.visible">
            <el-radio
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="是否展示父级" prop="isShowParent">-->
<!--          <el-input v-model="form.isShowParent" placeholder="请输入是否展示父级" />-->
<!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBi_show, getBi_show, delBi_show, addBi_show, updateBi_show } from "@/api/bi/bi_show";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Bi_show",
  dicts: ['zx_menu_type', 'sys_yes_no'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 产品展示信息表格数据
      bi_showList: [],
      // 产品展示信息树选项
      bi_showOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        menuName: null,
        parentId: null,
        menuLogo: null,
        menuTitle: null,
        orderNum: null,
        showUrl: null,
        fileUrl: null,
        menuType: null,
        visible: null,
        isShowParent: null,
        icon: null,
      },
      savingOrderNum: null,
      savingVisible: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        menuName: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    formatUrl(url) {
      if (!url) return '';
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      return 'http://' + url; // 或 'https://' + url，根据你的业务决定
    },
    handleVisibleChange(row) {
      if (this.savingVisible === row.menuId) return; // 防止重复提交

      this.savingVisible = row.menuId;

      const originalValue = row.visible; // 保存原始值，用于失败回滚

      updateBi_show(row)
        .then(() => {
          this.$modal.msgSuccess("状态更新成功");
        })
        .catch(() => {
          // 回滚状态
          this.$set(row, 'visible', originalValue);
          this.$modal.msgError("状态更新失败");
        })
        .finally(() => {
          this.savingVisible = null;
        });
    },
    handleOrderNumChange(row) {
      if (this.savingOrderNum === row.menuId) return;

      const num = Number(row.orderNum);
      if (isNaN(num) || num < 0) {
        this.$modal.msgError("显示顺序必须为非负整数");
        return;
      }

      this.savingOrderNum = row.menuId;

      updateBi_show(row)
        .then(() => {
          this.$modal.msgSuccess("更新成功");
        })
        .catch(() => {
          this.$modal.msgError("更新失败");
        })
        .then(() => {
          // 无论成功失败都执行
          this.savingOrderNum = null;
        });
    },
    /** 查询产品展示信息列表 */
    getList() {
      this.loading = true;
      listBi_show(this.queryParams).then(response => {
        this.bi_showList = this.handleTree(response.data, "menuId", "parentId");
        this.loading = false;
      });
    },
    /** 转换产品展示信息数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      };
    },
	/** 查询产品展示信息下拉树结构 */
    getTreeselect() {
      listBi_show().then(response => {
        this.bi_showOptions = [];
        const data = { menuId: 0, menuName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "menuId", "parentId");
        this.bi_showOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        menuId: null,
        menuName: null,
        parentId: null,
        menuLogo: null,
        menuTitle: null,
        orderNum: null,
        showUrl: null,
        fileUrl: null,
        menuType: null,
        visible: null,
        isShowParent: null,
        icon: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.menuId) {
        this.form.parentId = row.menuId;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加产品展示信息";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.parentId;
      }
      getBi_show(row.menuId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改产品展示信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.menuId != null) {
            updateBi_show(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBi_show(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除产品展示信息编号为"' + row.menuId + '"的数据项？').then(function() {
        return delBi_show(row.menuId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
